#!/usr/bin/env bash
set -eo pipefail
[[ $DOKKU_TRACE ]] && set -x
source "$PLUGIN_CORE_AVAILABLE_PATH/common/functions"
source "$PLUGIN_CORE_AVAILABLE_PATH/common/property-functions"

trigger-builder-herokuish-post-app-clone-setup() {
  declare desc="builder-herokuish post-app-clone-setup plugin trigger"
  declare trigger="post-app-clone-setup"
  declare OLD_APP="$1" NEW_APP="$2"

  local OLD_CACHE_DIR="$DOKKU_ROOT/$OLD_APP/cache"
  local OLD_CACHE_HOST_DIR="$DOKKU_HOST_ROOT/$OLD_APP/cache"

  if [[ -d "$OLD_CACHE_DIR" ]] && ! rmdir "$OLD_CACHE_DIR" >/dev/null 2>&1; then
    local DOCKER_RUN_LABEL_ARGS="--label=com.dokku.app-name=$NEW_APP"
    "$DOCKER_BIN" container run "${DOCKER_RUN_LABEL_ARGS[@]}" $DOKKU_GLOBAL_RUN_ARGS --rm --volume "$OLD_CACHE_HOST_DIR:/cache" "dokku/$OLD_APP" chmod 777 -R /cache
  fi
  rm -rf "$OLD_CACHE_DIR"

  pushd "$DOKKU_ROOT/$OLD_APP/." >/dev/null
  find ./* \( -name ".cache" -o -name "cache" \) -prune -o -print | cpio -pdmu --quiet "$DOKKU_ROOT/$NEW_APP"
  popd >/dev/null 2>&1 || pushd "/tmp" >/dev/null
}

trigger-builder-herokuish-post-app-clone-setup "$@"
